<template>
  <Dialog :title="comInfo.name" :show="true" @close="cancel" :width="580" :height="350" :left="uiLeft" :top="uiTop">
    <div class="cimrts-menu">
      <div class="menu-left">
        <FucMenuList :menuList="clippingMenuList" @clickComponent="clickComponent" :isDisabled="false"
          :isChecked="true" />
      </div>

      <div class="menu-right">
        <el-button @click.stop="BatchDelete" class="alert-btn"> 批量删除</el-button>
        <el-button @click=" currentDialog = 'submit'"> 提交</el-button>
      </div>
    </div>
    <div class="center-table">
      <el-table :data="clipListsRef" border :cell-style="cellStyle2" :header-cell-style="cellStyleSmall"
        :highlight-current-row="false" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="index" label="序号" width="60" align="center" :show-overflow-tooltip="true" /> -->
        <el-table-column type="selection" width="35" align="center" />
        <el-table-column prop="name" align="center" label="名称" width="90" :show-overflow-tooltip="true" />
        <el-table-column prop="operation" align="center" label="类型" width="130" :show-overflow-tooltip="true">
          <template #default="scope">
            <div class="table-operation">
              <div class="switch">外部<el-switch v-model="scope.row.type" size="small" />内部</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="auto">
          <template #default="scope">
            <div id="table-operation">
              <el-button size="small" text @click="locationClipPolygon(scope.row)">
                <img src="@/assets/common/dingwei.png" /> 定位
              </el-button>
               <el-button size="small" text @click="edit(scope.row)">
                <img src="@/assets/common/editing.png" /> 编辑
              </el-button>
              <el-button size="small" text @click="modifyClipPolygonName(scope.row)">
                <img src="@/assets/common/name.png" /> 修改名称
              </el-button>
              <el-button size="small" text @click="deleteClip(scope.row)">
                <img src="@/assets/common/shanchu.png" /> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </Dialog>
  <TooltipCom v-if="currentDialog == 'submit'" :content="'确认提交吗？'" :title="'提交'" :isVisible="true"
    @close="currentDialog = undefined" @confirm="submitConfirm" />

  <TooltipCom v-if="currentDialog == 'delete'" :content="'确认删除吗？'" :title="'删除'" :isVisible="true"
    @close="currentDialog = undefined" @confirm="deleteConfirm" />

  <TooltipCom v-if="currentDialog == 'batchDel'" :content="'确认删除吗？'" :title="'批量删除'" :isVisible="true"
    @close="currentDialog = undefined" @confirm="batchDelConfirm" />

  <DialogCom v-if="currentDialog == 'modifyClipPolygonName'" :draggable="true" :title="'修改裁剪区域名称'" :visible="true"
    :content="'确认提交吗？'" @close="currentDialog = undefined" @confirm="confirmModifyClipPolygonName">
    <template v-slot:content>
      <div class="clip_box">
        <div class="clip_title">名称:</div>
        <el-input v-model="clipPolygonName" class="ipt" />
      </div>
    </template>
  </DialogCom>

  <UploadShp v-if="currentDialog == 'uploadShp'" :title="'上传SHP'" :isVisible="true" @close="currentDialog = undefined"
    @confirm="confirmUploadShp" type="ClippingArea"></UploadShp>

  <UploadGeoJson v-if="currentDialog == 'geojson'" :title="'上传GeoJSON'" :isVisible="true"
    @close="currentDialog = undefined" @confirm="confirmUploadGeoJSON" type="ClippingArea"></UploadGeoJson>

  <TooltipCom v-if="currentDialog == 'shpLength'" :content="`创建的裁剪区域数量为 ${shpInfo.features.length} 个，超过了最大创建数100个。点击确定后请稍等，系统将只创建前100个要素。您是否要继续？
`" :title="'提示'" :isVisible="true" @close="currentDialog = undefined" @confirm="confirmShpLength" />

  <TooltipCom v-if="currentDialog == 'geojsonLength'" :content="`创建的裁剪区域数量为 ${geojsonInfo.features.length} 个，超过了最大创建数100个。点击确定后请稍等，系统将只创建前100个要素。您是否要继续？
`" :title="'提示'" :isVisible="true" @close="currentDialog = undefined" @confirm="confirmGeoJsonLength" />
</template>
<script setup lang="ts">

import { clippingMenuList } from "@/scripts/menu/modelser2/clippingMenuList";
import Dialog from "@/components/Dialog.vue";
import DialogCom from "@/components/common/DialogCom.vue";
import { onBeforeUnmount, onMounted, ref, watch, nextTick } from "vue";
import { cellStyle2, cellStyleSmall } from "../../scripts/tableStyle";
import { getProjectManager } from "../../scripts/getProjectManager";
import { createVueDisposer, toVR, } from "earthsdk-ui";
import TooltipCom from "../../components/common/TooltipCom.vue";
import { ElMessage } from "element-plus";
import FucMenuList from "@/components/common/FucMenuList.vue";
import UploadShp from "./UploadShp.vue";
import UploadGeoJson from "./UploadGeoJson.vue";

const props = withDefaults(defineProps<{ comInfo: any }>(), {});
const emits = defineEmits(["cancel"]);
const cancel = () => {
  emits("cancel", props.comInfo.id);
};
const uiLeft = document.body.clientWidth - 10 - 580;

const uiTop = 60

const d = createVueDisposer(onBeforeUnmount);

const objm = getProjectManager();
const modelser2Manager = objm.modelser2Manager;
const clippingArea = modelser2Manager.clippingArea as any
// 裁剪区域列表
const clipListsRef = toVR<any>(d, [clippingArea, "clipLists"]);

const currentDialog = ref<any>(undefined)
const items = ref([])

// 鼠标点击组件

const clickComponent = (item: any) => {
  if (item.id === 'submit') {
    currentDialog.value = 'submit'
    return;
  }
  if (item.id === 'shp') {
    currentDialog.value = 'uploadShp'
    return;
  }
  if (item.id === 'geojson') {
    currentDialog.value = 'geojson'
    return;
  }
  if (item.id === 'download') {
    if (!items.value.length) {
      ElMessage({
        message: '请先勾选裁剪区域',
        type: 'warning',
      })
    } else {
      modelser2Manager.downloadGeoJSON(items.value, "裁剪区域")
    }
    return;
  }
  clippingArea.createEvent.emit(item.id)
  item.status != "active" ? item.status = "active" : item.status = "none";
  if (item.status == "none") {
    clippingArea.createEvent.emit("")
  }
}

// 提交 确定
const submitConfirm = async () => {
  await clippingArea.createClipPolygon()
  currentDialog.value = undefined

}



// 定位
const locationClipPolygon = (row: any) => {
  const sceneObject = clippingArea.clipMap.get(row.id)
  sceneObject.flyTo()
}

// 编辑
const edit = (row: any) => {
  const sceneObject = clippingArea.clipMap.get(row.id)
  sceneObject.editing = true
}

const clipPolygonName = ref("")
let selectedClipId = ref("")

// 修改
const modifyClipPolygonName = (row: any) => {
  clipPolygonName.value = row.name
  selectedClipId.value = row.id
  currentDialog.value = 'modifyClipPolygonName'
}

// 修改名称 确定
const confirmModifyClipPolygonName = () => {
  const index = clipListsRef.value.findIndex((item: any) => item.id === selectedClipId.value)
  const item = clipListsRef.value[index]
  item.name = clipPolygonName.value
  clipListsRef.value.splice(index, 1, item)
  ElMessage.success("修改成功")
  currentDialog.value = undefined
}

// 删除
const deleteClip = (row: any) => {
  selectedClipId.value = row.id
  currentDialog.value = 'delete'
}

// 删除 确定
const deleteConfirm = () => {
  const index = clipListsRef.value.findIndex((item: any) => item.id === selectedClipId.value)
  clipListsRef.value.splice(index, 1)
  if (clippingArea.clipMap.has(selectedClipId.value)) {
    objm.destroySceneObject(clippingArea.clipMap.get(selectedClipId.value))
    clippingArea.clipMap.delete(selectedClipId.value)
  }
  ElMessage.success("删除成功")
  currentDialog.value = undefined
}

const ids = ref([])

/** 多选 拿到id数组*/
const handleSelectionChange = (val: any) => {
  items.value = val
  ids.value = val.map((item: any) => item.id)
}


// 批量删除
const BatchDelete = () => {
  if (ids.value.length == 0) return ElMessage.error('请先勾选裁剪区域')
  currentDialog.value = 'batchDel'
}

const batchDelConfirm = () => {
  ids.value.forEach((id) => {
    const index = clipListsRef.value.findIndex((item: any) => item.id == id)
    clipListsRef.value.splice(index, 1)
    if (clippingArea.clipMap.has(id)) {
      objm.destroySceneObject(clippingArea.clipMap.get(id))
      clippingArea.clipMap.delete(id)
    }
  })
  currentDialog.value = undefined
  ElMessage.success('删除成功')
}

const shpInfo = ref<any>([])

// 上传SHP确定
const confirmUploadShp = (data: any) => {
  shpInfo.value = []
  if (data.features.length > 100) {
    currentDialog.value = "shpLength"
    shpInfo.value = data
  } else {
    clippingArea.createPolygonsByShp(data)
    currentDialog.value = undefined
  }
}
const confirmShpLength = () => {
  const { features, ...e } = shpInfo.value
  const data = {
    features: features.slice(0, 100),
    ...e
  }
  clippingArea.createPolygonsByShp(data)
  currentDialog.value = undefined
}

const geojsonInfo = ref<any>([])


// 上传geojson确定
const confirmUploadGeoJSON = (data: any) => {
  geojsonInfo.value = []
  if (data.features.length > 100) {
    currentDialog.value = "geojsonLength"
    geojsonInfo.value = data
  } else {
    clippingArea.createPolygonsByGeonJson(data)
    currentDialog.value = undefined
  }
}

const confirmGeoJsonLength = () => {
  const { features, ...e } = geojsonInfo.value
  const data = {
    features: features.slice(0, 100),
    ...e
  }
  clippingArea.createPolygonsByShp(data)
  currentDialog.value = undefined
}

onMounted(async () => {
  await clippingArea.getClipPolygon()
})

onBeforeUnmount(() => {
  clippingArea.clear()
})

</script>
<style scoped>
.center-table {
  height: calc(100% - 60px);
  padding: 10px;
}

.cimrts-menu {
  background-color: #f0f0f0;
  width: calc(100%);
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px 0 0;
  box-sizing: border-box;
}

#table-operation img {
  width: 17px !important;
  height: 18px !important;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover>td) {
  background-color: transparent !important;
  color: #333 !important;

}

:deep(.el-table) {
  height: 100%;
  overflow-y: auto;
}

.switch {
  display: flex;
  justify-content: space-around;
}

.clip_title {
  width: 70px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.clip_box {
  display: flex;
  margin-bottom: 15px;
}

.menu-left {
  width: 60%;
}

/* 批量删除按钮 */
.alert-btn {
  color: #F96F70;
  border: 1px solid #F96F70;
  background-color: rgba(249, 111, 112, 0);
}

.alert-btn:hover {
  color: #F96F70;
  border: 1px solid #F96F70;
  background-color: rgba(249, 111, 112, 0);
}

#table-operation .el-button+.el-button {
  margin-left: 0px;
}
</style>
